package edu.hawaii.duedates;

import java.util.List;
import java.util.ArrayList;
import edu.hawaii.duedates.libraries.UhManoaLibraryQuery;

/**
 * Command line parser class.
 * 
 * @author Daniel Tian
 * @author Aric West
 * 
 */
public class CommandLineParser {
  private final List<LenderQuery> lenderList;
  private final String[] args;
  private LenderQuery lender;
  List<String> fieldList = new ArrayList<String>();
  /**

   * Constructor. Goes through all the command-line arguments and creates instances of all the
   * lender classes and passes the proper fields to them.
   * 
   * @param theArgs the arguments from the command line
   */
  public CommandLineParser(String[] theArgs) {
    lenderList = new ArrayList<LenderQuery>();
    this.args = theArgs.clone();
  }

  /**
   * Parses command-line arguments and instantiates the proper classes.
   * 
   * @throws Exception thrown if the number of fields is not the same as what the class expected
   */
  public void parseArguments() throws Exception {
    if (args.length > 0) {
      for (int i = 0; i < args.length; i++) {
        if (args[i++].equals("-uhm")) {
          while (i < args.length && !args[i].startsWith("-")) {
            fieldList.add(args[i++]);
          }

          lender = new UhManoaLibraryQuery();

          if (fieldList.size() == lender.getExpectedFieldLength()) {
            lender.setFields(fieldList);
          }
          else {
            throw new Exception("The library -uhm expected " + lender.getExpectedFieldLength()
                + " fields but got " + fieldList.size() + " instead.");
          }

          lenderList.add(lender);
          fieldList.clear();
        }
        else {
          System.out.println("No command-line arguments provided.");
        }
      }
    }
  }

  /**
   * Returns the list of instantiated lenders.
   * 
   * @return The list of instantiated lenders.
   * @throws Exception thrown if the number of fields is not the same as what the class expected
   */
  public List<LenderQuery> getLenderList() throws Exception {
    this.parseArguments();
    
    return lenderList;
  }
}
